package data;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class ReadDatabase {
	
	private BufferedReader buffReader;
	private ArrayList<Team> teams;
	private int maxRiders = 100;
	
	public ArrayList<Cyclist> ReadFromFileCyclists(String path) {

		ArrayList<Cyclist> cyclist;
		File file = new File(path);
	    int length = 0;
		String[] lines = new String[maxRiders];
		try {
			FileReader reader = new FileReader(file);
			buffReader = new BufferedReader(reader);
			String s;
			
			while((s = buffReader.readLine()) != null){
				lines[length] = s;
				length++;
		    }
		}
		catch(IOException e) {
			System.out.println("I cannot open file!");
		}
		
		cyclist = new ArrayList<Cyclist>(length);
		
		for(int i = 0; i < length; i++) {
			StringTokenizer st  = new StringTokenizer(lines[i], "	");
			 while (st.hasMoreTokens()) {
				 cyclist.add(new Cyclist(i));
				 cyclist.get(i).setSurname(st.nextToken());
				 cyclist.get(i).setFirstName(st.nextToken());
				 cyclist.get(i).setNation(st.nextToken());
				 String tmp = st.nextToken();
				 cyclist.get(i).setTeamName(tmp);
				 addToTeam(tmp, i);
				 cyclist.get(i).setFlat(Integer.parseInt(st.nextToken()));
				 cyclist.get(i).setMountains(Integer.parseInt(st.nextToken()));
				 cyclist.get(i).setHills(Integer.parseInt(st.nextToken()));
				 cyclist.get(i).setTimeTrial(Integer.parseInt(st.nextToken()));
				 cyclist.get(i).setDownhill(Integer.parseInt(st.nextToken()));
				 cyclist.get(i).setStamina(Integer.parseInt(st.nextToken()));
				 cyclist.get(i).setRecovery(Integer.parseInt(st.nextToken()));
				 cyclist.get(i).setSprint(Integer.parseInt(st.nextToken()));
				 cyclist.get(i).setCobble(Integer.parseInt(st.nextToken()));	
				 cyclist.get(i).setRole(Integer.parseInt(st.nextToken()));
				 cyclist.get(i).setSpecial();
		     }
		}	
		
		return cyclist;
	}
	
	public ArrayList<Team> ReadFromFileTeams(String path) {
		
		teams = new ArrayList<Team>();
		File file = new File(path);
	    int length = 0;
		try {
			FileReader reader = new FileReader(file);
			buffReader = new BufferedReader(reader);
			String s;
			
			while((s = buffReader.readLine()) != null){
				 teams.add(new Team(length));
				 teams.get(length).setTeamName(s);
				 length++;
		    }
		}
		catch(IOException e) {
			System.out.println("I cannot open file!");
		}		
		
		return teams;		
	}	
	
	
	public void addToTeam(String team, int id) {
		
		Boolean unDone = true;
		int ptr = 0;
		
		while (unDone) {
			if (team.equals(teams.get(ptr).getTeamName())) {
				teams.get(ptr).addRider(id);
				unDone = false;
			}
			ptr++;
		}
		
	}
}
